package com.heima.leetcode.practice;

import java.util.LinkedList;
import java.util.Objects;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 71. 简化路径
 * @date 2025/5/14 10:57
 */
public class E71 {

    /**
     * 方法一：自己用IDEA一个一个情况debug调出来的。
     * @param path 路径
     * @return 简化后的路径
     */
    public String simplifyPath(String path) {
        LinkedList<String> deque = new LinkedList<>();
        deque.offer("/");
        StringBuilder builder = new StringBuilder();
        for (char c : path.toCharArray()) {
            if (c == '.') {
                builder.append('.');
            } else if (c == '/') {
                if (!builder.isEmpty()
                        && !builder.toString().equals(".")
                        && !builder.toString().equals("..")) {
                    deque.offer(builder.toString());
                }
                if (Objects.equals(deque.peekLast(), "/")
                        && !builder.toString().equals(".")
                        && !builder.toString().equals("..")) {
                    continue;
                } else if (builder.toString().equals(".")) {
                    builder.setLength(0);
                } else if (builder.toString().equals("..")) {
                    deque.pollLast();
                    deque.pollLast();
                    builder.setLength(0);
                    if (deque.isEmpty()) deque.offer("/");
                } else {
                    builder.setLength(0);
                    deque.offer("/");
                }
            } else {
                builder.append(c);
            }
        }
        if (!builder.isEmpty()) {
            if (builder.toString().equals("..")) {
                deque.pollLast();
                deque.pollLast();
                if (deque.isEmpty()) deque.offer("/");
            } else if (builder.toString().equals(".")) {
                // do nothing
            } else {
                deque.offer(builder.toString());
                deque.offer("/");
            }
        }
        builder.setLength(0);
        for (String str : deque) {
            builder.append(str);
        }
        if (builder.length() > 1) {
            builder.deleteCharAt(builder.length() - 1);
        }
        return builder.toString();
    }
}
